package jdbcinterface;

import java.rmi.RemoteException;
import java.sql.*;

import SQL.planner.Planner;
import SQL.query.SQL;
import SQL.query.Select;

import Common.GoggleDB;

import rmi.RemoteResultSet;
import rmi.RemoteStatement;
import rmi.StatementAdapter;


public class GoggleStatement extends StatementAdapter {
	private RemoteStatement rstmt;
	private GoggleResultSet cRes = null ;
	int affectedLines = 0 ; 

	public GoggleStatement(RemoteStatement s) {
		rstmt = s;
	}

	public boolean execute(String qry) throws SQLException {
		try {
			String qrys [] = qry.split( ";") ;
			for ( int i = 0 ; i < qrys.length-1 ; i ++  ) {
				SQL sql=Planner.getSQL(qrys[i]);
				if (sql instanceof Select)
				{
					RemoteResultSet rrs = rstmt.executeQuery(qrys[i]);
					cRes = new GoggleResultSet(rrs);
				}
				else
				{
					affectedLines = rstmt.executeUpdate(qrys[i]);
				}
			}
			SQL sql=Planner.getSQL(qrys[qrys.length-1]);
			if (sql instanceof Select)
			{
				RemoteResultSet rrs = rstmt.executeQuery(qrys[qrys.length-1]);
				cRes = new GoggleResultSet(rrs);
				return true;
			}
			else
			{
				affectedLines = rstmt.executeUpdate(qrys[qrys.length-1]);
				return false;
			}
		}
		catch(RemoteException e) {
			throw new SQLException(e.toString() );
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false ;
	}
	
	public ResultSet executeQuery(String qry) throws SQLException {
		try {
			RemoteResultSet rrs = rstmt.executeQuery(qry);
			cRes = new GoggleResultSet(rrs); 
			return cRes ; 
		}
		catch(RemoteException e) {
			throw new SQLException(e.toString() );
		}
	}

	public int executeUpdate(String cmd) throws SQLException {
		try {
			return ( affectedLines = rstmt.executeUpdate(cmd) );
		}
		catch(RemoteException e) {
			e.printStackTrace() ; 
			throw new SQLException(e.toString() );
		}
	}
	
	public ResultSet getResultSet() throws SQLException {
		return cRes ;
	}
	
	public int getUpdateCount() throws SQLException {
		return affectedLines ; 
	}
	
	public void setMaxRows(int max) { 
	}
	
}

